package io.yyxx.boot.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.yyxx.boot.business.entity.time.YidaLastSyncTime;
import io.yyxx.boot.business.mapper.YidaLastSyncTimeMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 获取最后同步时间和想数据库更新时间
 */
@Component
public class LastSyncTimeUtil {
    @Resource
    YidaLastSyncTimeMapper yidaLastSyncTimeMapper;

    /**
     * 获取最后同步时间
     */
    public LocalDateTime getLastSyncTime(String lastSyncTime) {
        // 使用MyBatis-Plus的条件构造器
        QueryWrapper<YidaLastSyncTime> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("last_time", lastSyncTime);

        YidaLastSyncTime timestamp = yidaLastSyncTimeMapper.selectOne(queryWrapper);

        if (timestamp != null) {
            return timestamp.getValue();
        } else {
            // 初始化时间戳
            LocalDateTime initTime = LocalDateTime.of(1970, 1, 1, 0, 0);
            YidaLastSyncTime newTimestamp = new YidaLastSyncTime();
            newTimestamp.setLastTime(lastSyncTime);
            newTimestamp.setValue(initTime);
            newTimestamp.setUpdateTime(LocalDateTime.now());
            yidaLastSyncTimeMapper.insert(newTimestamp);
            return initTime;
        }
    }

    /**
     * 更新时间戳记录
     */
    public void updateSyncTimestamp(LocalDateTime timestamp, String lastSyncsTime) {
        // 构造更新对象
        YidaLastSyncTime updateEntity = new YidaLastSyncTime();
        updateEntity.setLastTime(lastSyncsTime);
        updateEntity.setValue(timestamp);
        updateEntity.setUpdateTime(LocalDateTime.now());

        // 使用MyBatis-Plus的插入或更新
        QueryWrapper<YidaLastSyncTime> wrapper = new QueryWrapper<>();
        wrapper.eq("last_time", lastSyncsTime);

        if (yidaLastSyncTimeMapper.exists(wrapper)) {
            yidaLastSyncTimeMapper.update(updateEntity, wrapper);
        } else {
            yidaLastSyncTimeMapper.insert(updateEntity);
        }
    }
}
